//
//  NSArray+GL.m
//  GLLibDemo
//
//  Created by huang long on 17/5/8.
//  Copyright © 2017年 历山大亚. All rights reserved.
//

#import "NSArray+GL.h"
#import <objc/runtime.h>

@implementation NSArray (GL)


+ (void)load{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Class class = objc_getClass("__NSArrayI");
        SEL originalSelector = @selector(objectAtIndex:);
        SEL swizzledSelector = @selector(gl_objectAtIndex:);
        
        Method originalMethod = class_getInstanceMethod(class, originalSelector);
        Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
        
        BOOL didAddMethod =
        class_addMethod(class,
                        originalSelector,
                        method_getImplementation(swizzledMethod),
                        method_getTypeEncoding(swizzledMethod));
        
        if (didAddMethod) {
            class_replaceMethod(class,
                                swizzledSelector,
                                method_getImplementation(originalMethod),
                                method_getTypeEncoding(originalMethod));
        } else {
            method_exchangeImplementations(originalMethod, swizzledMethod);
        }
        //  替换可变数组中的方法
        Method oldMutableObjectAtIndex1 = class_getInstanceMethod(objc_getClass("__NSArrayM"), @selector(objectAtIndex:));
        Method newMutableObjectAtIndex1 =  class_getInstanceMethod(objc_getClass("__NSArrayM"), @selector(mutable_objectAtIndex:));
        method_exchangeImplementations(oldMutableObjectAtIndex1, newMutableObjectAtIndex1);
        
        
        //  替换可变数组中的方法
        Method oldMutableObjectAtIndex2 = class_getInstanceMethod(objc_getClass("__NSArrayM"), @selector(removeObjectAtIndex:));
        Method newMutableObjectAtIndex2 =  class_getInstanceMethod(objc_getClass("__NSArrayM"), @selector(mutable_removeObjectAtIndex:));
        method_exchangeImplementations(oldMutableObjectAtIndex2, newMutableObjectAtIndex2);
    });
}




//objectAtIndexedSubscript  最后还是会掉用 objectAtIndex方法
- (id)gl_objectAtIndex:(NSUInteger)idx{
    
    if (idx >= self.count) {
        NSLog(@"%s哥们 数组越界啦",__FUNCTION__);
        return nil;
    }
    return [self gl_objectAtIndex:idx];
}

- (id)mutable_objectAtIndex:(NSUInteger)idx{
    if (idx >= self.count) {
        NSLog(@"%s哥们 数组越界啦",__FUNCTION__);
        return nil;
    }
    return [self mutable_objectAtIndex:idx];
}

- (void)mutable_removeObjectAtIndex:(NSUInteger)index{
    if (self.count > index) {
        [self mutable_removeObjectAtIndex:index];
    }else{
        NSLog(@"%s哥们 数组越界啦",__FUNCTION__);
    }
}

@end
